<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Highcharts Demo</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">
	</head>
	<body>
		<h2 id="wait">Loading lib....</h2>

		<script src="https://code.highcharts.com/highcharts.js"></script>
		<script src="https://code.highcharts.com/modules/boost.js"></script>

		<div id="container" style="height: 600px; max-width: 1920px; margin: 0 auto"></div>

		<script>
			function round2(val) {
				return Math.round(val * 100) / 100;
			}

			function round3(val) {
				return Math.round(val * 1000) / 1000;
			}

			function prepData(packed) {
				console.time('prep');

				// epoch,idl,recv,send,read,writ,used,free

				const numFields = packed[0];
				packed = packed.slice(numFields + 1);

				var cpu = Array(packed.length/numFields);
				var ram = Array(packed.length/numFields);
				var tcp = Array(packed.length/numFields);

				for (let i = 0, j = 0; i < packed.length; i += numFields, j++) {
					let date = packed[i] * 60 * 1000;
					cpu[j] = [date, round3(100 - packed[i+1])];
					ram[j] = [date, round2(100 * packed[i+5] / (packed[i+5] + packed[i+6]))];
					tcp[j] = [date, packed[i+3]];
				}

				console.timeEnd('prep');

				return [cpu, ram, tcp];
			}

			function makeChart(data) {
				console.time('chart');

				Highcharts.chart('container', {
					boost: {
						useGPUTranslations: true,
						seriesThreshold: 1,
					},
					chart: {
						zoomType: 'x',
						animation: false,
						events: {
							render: () => {
								wait.textContent = "Done!";
								console.timeEnd('chart');
							}
						},
					},
					title: {
						text: 'Highcharts (' + data[0].length * 3 + ' points)'
					},
					subtitle: {
						text: 'Using the Boost module'
					},
					tooltip: {
						valueDecimals: 2,
						animation: false,
					},
					xAxis: {
						type: 'datetime'
					},
					plotOptions: {
						line: {
							marker: {
								enabled: false
							}
						}
					},
					series: [
						{
							data: data[0],
							lineWidth: 1,
							name: 'CPU',
							boostThreshold: 1,
							turboThreshold: 1,
						},
						{
							data: data[1],
							lineWidth: 1,
							name: 'RAM',
							boostThreshold: 1,
							turboThreshold: 1,
						},
						{
							data: data[2],
							lineWidth: 1,
							name: 'TCP Out',
							boostThreshold: 1,
							turboThreshold: 1,
						}
					]
				});
			}

			let wait = document.getElementById("wait");
			wait.textContent = "Fetching data.json (2.07MB)....";
			fetch("data.json").then(r => r.json()).then(packed => {
				wait.textContent = "Rendering...";
				let data = prepData(packed);
				setTimeout(() => makeChart(data), 0);
			});
		</script>
	</body>
</html>